package com.cysion.otbox.ext

import com.tencent.mmkv.MMKV

/*
* 键值对 key-对象 扩展
* */


/*
* 放入对象,先将对象转成json，然后存储
* 对于那些基本的类型，比如Int,String，应该用mmkv原生encode方法
* */
fun MMKV.putObj(key: String, t: Any) {
    when (t::class.java) {
        Int::class.java -> {
            t as Int
            encode(key, t)
            return
        }
        Long::class.java -> {
            t as Long
            encode(key, t)
            return
        }
        Double::class.java -> {
            t as Double
            encode(key, t)
            return
        }
        Float::class.java -> {
            t as Float
            encode(key, t)
            return
        }
        String::class.java -> {
            t as String
            encode(key, t)
            return
        }
        Boolean::class.java -> {
            t as Boolean
            encode(key, t)
            return
        }
    }
    val json = gson.toJson(t)
    encode(key, json)
}

inline fun <reified T> MMKV.getObj(key: String): T? {
    when (T::class.java) {
        Int::class.java -> {
            return decodeInt(key) as T
        }
        Long::class.java -> {
            return decodeLong(key) as T
        }
        Double::class.java -> {
            return decodeDouble(key) as T
        }
        Float::class.java -> {
            return decodeFloat(key) as T
        }
        String::class.java -> {
            return decodeString(key) as T
        }
        Boolean::class.java -> {
            return decodeBool(key) as T
        }
    }
    val json = decodeString(key)
    return gson.fromJson<T>(json)
}

